package com.zenithmind.document.pojo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * 文档权限更新DTO
 * 遵循单一职责原则：专注于权限更新数据传输
 * 遵循开闭原则：支持字段的扩展
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "文档权限更新DTO")
public class DocumentPermissionUpdateDTO {

    @Schema(description = "目标名称", example = "张三")
    private String targetName;

    @Schema(description = "权限类型", example = "READ", allowableValues = {"read", "write", "delete", "share", "admin"})
    private String permissionType;

    @Schema(description = "权限值", example = "ALLOW", allowableValues = {"ALLOW", "DENY", "INHERIT"})
    private String permissionValue;

    @Schema(description = "权限级别", example = "2")
    private Integer permissionLevel;

    @Schema(description = "权限范围", example = "DOCUMENT", allowableValues = {"DOCUMENT", "FOLDER", "CATEGORY", "GLOBAL"})
    private String permissionScope;

    @Schema(description = "权限条件", example = "{\"timeRange\": \"09:00-18:00\", \"ipWhitelist\": [\"192.168.1.0/24\"]}")
    private String permissionCondition;

    @Schema(description = "是否继承", example = "true")
    private Boolean isInherited;

    @Schema(description = "父权限ID", example = "perm123456")
    private String parentPermissionId;

    @Schema(description = "优先级", example = "150")
    private Integer priority;

    @Schema(description = "生效时间", example = "2025-01-09T00:00:00")
    private LocalDateTime effectiveTime;

    @Schema(description = "过期时间", example = "2025-12-31T23:59:59")
    private LocalDateTime expirationTime;

    @Schema(description = "授权原因", example = "权限调整")
    private String grantReason;

    @Schema(description = "权限标签", example = "调整后权限,项目相关")
    private String permissionTags;

    @Schema(description = "是否可委托", example = "true")
    private Boolean isDelegatable;

    @Schema(description = "最大委托层级", example = "3")
    private Integer maxDelegationLevel;

    @Schema(description = "委托限制", example = "{\"maxUsers\": 10, \"timeLimit\": \"14d\"}")
    private String delegationRestrictions;

    @Schema(description = "审批状态", example = "APPROVED", allowableValues = {"PENDING", "APPROVED", "REJECTED", "REVOKED"})
    private String approvalStatus;

    @Schema(description = "审批人ID", example = "approver123")
    private String approverId;

    @Schema(description = "审批时间", example = "2025-01-09T10:00:00")
    private LocalDateTime approvalTime;

    @Schema(description = "审批意见", example = "权限调整已批准")
    private String approvalComment;

    @Schema(description = "权限描述", example = "更新后的权限描述")
    private String description;

    @Schema(description = "扩展属性", example = "{\"department\": \"IT\", \"project\": \"ProjectB\"}")
    private String extendedProperties;

    @Schema(description = "备注", example = "权限更新备注")
    private String remarks;

    @Schema(description = "更新人ID", example = "updater123")
    private String updaterId;

    @Schema(description = "更新原因", example = "业务需求变更")
    private String updateReason;

    @Schema(description = "是否启用", example = "true")
    private Boolean isEnabled;

    @Schema(description = "状态", example = "ACTIVE", allowableValues = {"ACTIVE", "INACTIVE", "SUSPENDED", "EXPIRED"})
    private String status;

    /**
     * 验证更新数据
     */
    public boolean isValid() {
        // 验证时间范围
        if (effectiveTime != null && expirationTime != null) {
            return !effectiveTime.isAfter(expirationTime);
        }
        
        // 验证权限级别
        if (permissionLevel != null) {
            return permissionLevel >= 1 && permissionLevel <= 5;
        }
        
        // 验证优先级
        if (priority != null) {
            return priority >= 0 && priority <= 1000;
        }
        
        // 验证委托层级
        if (maxDelegationLevel != null) {
            return maxDelegationLevel >= 0 && maxDelegationLevel <= 10;
        }
        
        return true;
    }

    /**
     * 是否有权限类型更新
     */
    public boolean hasPermissionTypeUpdate() {
        return permissionType != null && !permissionType.trim().isEmpty();
    }

    /**
     * 是否有权限值更新
     */
    public boolean hasPermissionValueUpdate() {
        return permissionValue != null && !permissionValue.trim().isEmpty();
    }

    /**
     * 是否有时间范围更新
     */
    public boolean hasTimeRangeUpdate() {
        return effectiveTime != null || expirationTime != null;
    }

    /**
     * 是否有审批状态更新
     */
    public boolean hasApprovalStatusUpdate() {
        return approvalStatus != null && !approvalStatus.trim().isEmpty();
    }

    /**
     * 是否有委托设置更新
     */
    public boolean hasDelegationUpdate() {
        return isDelegatable != null || maxDelegationLevel != null || delegationRestrictions != null;
    }

    /**
     * 是否为权限升级
     */
    public boolean isPermissionUpgrade(Integer currentLevel) {
        return permissionLevel != null && currentLevel != null && permissionLevel > currentLevel;
    }

    /**
     * 是否为权限降级
     */
    public boolean isPermissionDowngrade(Integer currentLevel) {
        return permissionLevel != null && currentLevel != null && permissionLevel < currentLevel;
    }

    /**
     * 是否为临时权限设置
     */
    public boolean isTemporaryPermissionSetting() {
        return expirationTime != null && expirationTime.isAfter(LocalDateTime.now());
    }

    /**
     * 是否为永久权限设置
     */
    public boolean isPermanentPermissionSetting() {
        return expirationTime == null;
    }

    /**
     * 获取权限变更摘要
     */
    public String getChangeSummary() {
        StringBuilder summary = new StringBuilder();
        
        if (hasPermissionTypeUpdate()) {
            summary.append("权限类型: ").append(permissionType).append("; ");
        }
        
        if (hasPermissionValueUpdate()) {
            summary.append("权限值: ").append(permissionValue).append("; ");
        }
        
        if (permissionLevel != null) {
            summary.append("权限级别: ").append(permissionLevel).append("; ");
        }
        
        if (hasTimeRangeUpdate()) {
            summary.append("时间范围更新; ");
        }
        
        if (hasApprovalStatusUpdate()) {
            summary.append("审批状态: ").append(approvalStatus).append("; ");
        }
        
        if (hasDelegationUpdate()) {
            summary.append("委托设置更新; ");
        }
        
        return summary.length() > 0 ? summary.toString() : "无变更";
    }

    /**
     * 创建权限升级更新
     */
    public static DocumentPermissionUpdateDTO createUpgradeUpdate(String newPermissionType, String updaterId, String reason) {
        DocumentPermissionUpdateDTO dto = new DocumentPermissionUpdateDTO();
        dto.setPermissionType(newPermissionType);
        dto.setPermissionLevel(getPermissionLevel(newPermissionType));
        dto.setPriority(getPermissionPriority(newPermissionType));
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        dto.setApprovalStatus("PENDING");
        return dto;
    }

    /**
     * 创建权限延期更新
     */
    public static DocumentPermissionUpdateDTO createExtensionUpdate(LocalDateTime newExpirationTime, String updaterId, String reason) {
        DocumentPermissionUpdateDTO dto = new DocumentPermissionUpdateDTO();
        dto.setExpirationTime(newExpirationTime);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        dto.setApprovalStatus("PENDING");
        return dto;
    }

    /**
     * 创建权限暂停更新
     */
    public static DocumentPermissionUpdateDTO createSuspendUpdate(String updaterId, String reason) {
        DocumentPermissionUpdateDTO dto = new DocumentPermissionUpdateDTO();
        dto.setStatus("SUSPENDED");
        dto.setIsEnabled(false);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建权限恢复更新
     */
    public static DocumentPermissionUpdateDTO createResumeUpdate(String updaterId, String reason) {
        DocumentPermissionUpdateDTO dto = new DocumentPermissionUpdateDTO();
        dto.setStatus("ACTIVE");
        dto.setIsEnabled(true);
        dto.setUpdaterId(updaterId);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 获取权限级别
     */
    private static Integer getPermissionLevel(String permissionType) {
        switch (permissionType.toLowerCase()) {
            case "read": return 1;
            case "write": return 2;
            case "delete": return 3;
            case "share": return 4;
            case "admin": return 5;
            default: return 1;
        }
    }

    /**
     * 获取权限优先级
     */
    private static Integer getPermissionPriority(String permissionType) {
        switch (permissionType.toLowerCase()) {
            case "read": return 100;
            case "write": return 200;
            case "delete": return 300;
            case "share": return 400;
            case "admin": return 500;
            default: return 100;
        }
    }
}
